package com.eagle.roomcrawler.util;

import com.alibaba.fastjson.JSON;
import com.eagle.roomcrawler.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类，封装Redis方法
 */
@Repository
public class RedisUtil {

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    /**
     *如果键不存在则新增,存在则不改变已经有的值。
     * 存储key，value为时间戳 ,存在返回false
     * @param key
     */
    public Boolean  setIfAbsent(String key) {
        return stringRedisTemplate.opsForValue().setIfAbsent(key, ""+System.currentTimeMillis());
    }


    /**
     * 存储key，value为时间戳
     * @param key
     */
    public void add(String key) {
        stringRedisTemplate.opsForValue().increment(key, System.currentTimeMillis());
    }

    /**
     * 获取keys
     * @param pattern
     */
    public Set<String> getKeys(String pattern) {
        return stringRedisTemplate.keys(pattern);
    }

    public void add(String key, Object object, Long time) {
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(object), time, TimeUnit.MINUTES);
    }

    public void add(String key, List<Object> Object, Long time) {
        String src = JSON.toJSONString(Object);
        stringRedisTemplate.opsForValue().set(key, src, time, TimeUnit.MINUTES);
    }

    public User get(String key) {
        String source = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(source)) {
            return JSON.parseObject(source, User.class);
        }
        return null;
    }

    public List<Object> getObjectList(String key) {
        String source = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(source)) {
            return JSON.parseArray(source,Object.class);
        }
        return null;
    }

    public void delete(String key) {
        stringRedisTemplate.opsForValue().getOperations().delete(key);
    }
}
